package br.usp.icmc.biomac.client.view.impl;

import java.util.List;

import br.usp.icmc.biomac.client.view.DicomResultCellBrowser;
import br.usp.icmc.biomac.client.view.impl.PatientTreeModel.Series;
import br.usp.icmc.biomac.shared.CSVData;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.cellview.client.CellBrowser;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

public class DicomResultCellBrowserImpl extends DialogBox implements DicomResultCellBrowser {

	
	private static DicomResultCellBrowserImplUiBinder uiBinder = GWT
			.create(DicomResultCellBrowserImplUiBinder.class);

    Presenter presenter;   
	CellBrowser cellBrowser;	
	PatientTreeModel model;
	SingleSelectionModel<Series> selectionModel;

	
	interface DicomResultCellBrowserImplUiBinder extends
			UiBinder<Widget, DicomResultCellBrowserImpl> {
	}

	/**
     * Instantiates new browser dialog to select the image series.
	 * @author debra willrett
     *
     */
	public DicomResultCellBrowserImpl() {
	}
	
	
	@Override
	public void setPresenter(Presenter presenter) {
		// set the presenter for the cellbrowser
		this.presenter = presenter;
	}

	@Override
	public void setBrowserResult(List<CSVData> data) {
		// Add the data to the data provider, which automatically pushes it to
		// the widget.
		selectionModel = new SingleSelectionModel<Series>();
		model = new PatientTreeModel(selectionModel);
		model.setCsvData(data);
		
		// handle single selection event
		  selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {

		    public void onSelectionChange(SelectionChangeEvent event) {
		      // fire rpc, a place change or something else
		    	Series selected = selectionModel.getSelectedObject();
		        if (selected != null) {
	
		          // selected a series node, call the presenter to load the dicom images
		          presenter.loadBrowserResult(selected.getName());
		          DicomResultCellBrowserImpl.this.hide();
		        }
		    }
		  });
		 
		// create the browser and display it 
		cellBrowser = new CellBrowser(model, null);
	    cellBrowser.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
	    cellBrowser.setAnimationEnabled(true);
	    this.setAutoHideEnabled(true);
	    this.getElement().setId("browserDialog");
	    this.getElement().addClassName("imgGrid-widget cell-widget");

	    // have to set the size or the cellbrowser will not display	
	    cellBrowser.setHeight("300px");
	    cellBrowser.setWidth("600px");
 
	    // tell the dialog that this is the single widget
	    this.setWidget(cellBrowser);
	    this.setHTML("<div style='text-align:center'>Select Series</div>");
	    this.center();
	}

}
